package com.vogue.supplymall.common.domain.validate;

import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.common.exception.CheckLengthException;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import static com.vogue.supplymall.common.constant.ErrorCode.*;

/**
 * @aouthor: zhangliang
 * @date: Create in 2017-12-15
 */
public class LengthValidator implements ConstraintValidator<Length, String>, Serializable {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1095871724627495974L;
	
	@Autowired
	protected MessageSourceUtils messageSourceUtils;
	
	private int min;
    private int max;
    private String name = "name";

    @Override
    public void initialize(Length parameters) {
        min = parameters.min();
        max = parameters.max();
        name = messageSourceUtils.getMessage(com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
				+ parameters.name(), null);
        validateParameters();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        }
        int length = value.length();
        if (length > max) {
            throw new CheckLengthException(LengthOver.getCode(), name, Integer.toString(max));
        }
        if (length < min) {
            throw new CheckLengthException(LengthLose.getCode(), name, Integer.toString(min));
        }
        return length >= min && length <= max;
    }

    private void validateParameters() {
        if (min < 0) {
            throw new CheckLengthException(LengthError.getCode(), name, Integer.toString(min), Integer.toString(max));
        }
        if (max < 0) {
            throw new CheckLengthException(LengthError.getCode(), name, Integer.toString(min), Integer.toString(max));
        }
        if (max < min) {
            throw new CheckLengthException(LengthError.getCode(), name, Integer.toString(min), Integer.toString(max));
        }
    }
}
